Home | | Latest | About | Random
# Week 6 Wednesday
Dear Class,
Your exams and scores can be viewed on Gradescope. Please read through your exams and the comments we make, and redo the problems you missed and thoroughly understand how they work. Remember our goal is to learn C++. So focus on the learning. It is hard to say what that would translate to as a final grade, since our course grading scheme is designed to offer you opportunities to improve. So in some ways, you can think of this as a "trial run". However, I personally think if you have gotten 30 or more points out of 40, that's not bad, and you would want to really get back on track if you have gotten less than 20. Ultimately, the final exam will be quite a major determination, and it really will assess your understanding of what you learn in this course. I simultaneously want to encourage you but also caution you to not slack off or put things off too much. Try to diagnose what worked and what didn't. You can do it, I know you can!
Your midterm 2 exam on **Monday Week 8** will cover materials up to and including **HW4** and **section 14 function overloading**, you should absolutely review previous material as well.
**HW4** is due next **Wednesday at 10 pm**. It deals writing functions, deciding parameter types for your functions, const correctness, and dealing with multiple files, (`*.hpp` and `*.cpp`). There are videos on how to do deal with multiple files, `hpp` and `cpp` files in your IDE, which you can find in **Media Gallery** on **BruinLearn**.
Ok, today I want to discuss
- how to choose parameter types for functions
- `const` correctness
- having a multiple file `cpp` project by having
- header files `*.hpp` and implementation files `*.cpp`
-- B
.
.
.
.
.
## For functions, how do we pick the parameter type?
There are three options to pass an argument (of type `T`) into a parameter of a function
- `T`: by value
- `T&`: by reference
- `const T&`: by reference to `const`
We can ask:
| Do you want to mutate the argument? | Do you want to avoid copying it? | Use |
|---|---|---|
| Yes | Either | `T&` |
| No | Yes | `const T&` |
| No | No | `T` (simplest) |
Answering "Do you want to avoid copying it?" often boils down to whether the type of data being passed in is a class type or not:
- **Fundamental types:** These take about 1 to 8 bytes and are cheap to copy, so passing them by value is often fine.
- **Class types:** These can be huge, like a `std::string` holding all of Shakespeare or a large `std::vector`, so they're usually passed by `const T&`.
- This is a **rule of thumb** that works "in many situations, but not all."
### Const correctness matters when you work with others
- If a function doesn't change its argument and you want to avoid a copy, make the parameter a reference to `const` (`const T&`). The `&` avoids the copy, and the `const` tells the reader it won't be changed.
- Skipping `const` can break someone else's code.
- Say you have a function `sum` that takes a `vector&`,
- And you have another function `print_sum(const vector& data)` whose body calls `sum`. Then it won't build, even if `print_sum` is written correctly.
That is, we get a build error in this following code:
```cpp
#include
#include
using namespace std;
int sum(vector& data) {
int total = 0;
for (size_t i = 0 ; i < data.size(); i++){
total += data.at(i);
}
return total;
}
void print_sum(const vector& data) {
cout << sum(data) << endl;
}
int main() {
vector data = {1, 2, 3};
print_sum(data);
return 0;
}
```
- On which line does the compiler report an error? And what kind of error is it?
- Which line should you change to fix the error, and how?
Note, the line the compiler points to isn’t always the line you need to change!
(There are several ways to make `print_sum` above actually print out the sum, but one is much preferable. Can you determine which one?)
## Header files.
In creating a C++ project, you often will end up writing a lot of functions, which may clutter up the main `cpp` file. So a good practice is to split up the code in different files. Roughly we have two kinds
- `*.hpp` files (sometimes `.h`). These are **header files** that contain...
- Function declarations (and later, class definitions)
- Function comments as documentation
- Only the `#include`s the header itself need
- Avoid `using namespace` in a header file, since anyone who includes your header would be forced to use that namespace too.
- `*.cpp` files. These are **implementation files** that contain...
- Function definition (the actual body of the code of the functions)
- An `#include` of their own header: `my_stuff.cpp` should `#include "my_stuff.hpp"`
- Any other `#include`s the function bodies need
- `using namespace` is fine here, after the `#include`s
In fact, our `main.cpp` is also an implementation file, implementing the `main()` function, the entry point of our program. Of course the file does not have to be named `main.cpp`, but the project must have exactly one `main()` function.
So, a C++ project may consist of a list of files that look like this
```
my_functions.hpp
my_functions.cpp
other_stuff.hpp
other_stuff.cpp
main.cpp
```
### In class practice.
Let's practice separating this file into header file, implementation file, and a main cpp file. One should add comments and documentations, relevant includes, decide whether we should have `using namespace` or not.
Then, for practice, try adding in new function declarations and definitions. Some suggestions,
- a function called `average` that returns a `double` that is the average of the elements of the `vector` of `int`s.
- a function called `join` that returns a new `vector` of `int`s by joining two `vector`s of `int`s together
- a function called `append` that modifies a `vector` of `int`s by appending another `vector` of `int`s to its tail
- a function called `sequence` that gives a `vector` of `int`s that starts from `int a` up to possibly including `int b`, with some step size `t`. You will have to decide the implementation details and comment it appropriately.
- a function called `print` that simply prints out the entries of a `vector` of `int`s separated by *two spaces*, on its own line.
```cpp
#include
#include
using namespace std;
int sum(const vector& data) {
int total = 0;
for (size_t i = 0 ; i < data.size(); i++){
total += data.at(i);
}
return total;
}
void print_sum(const vector& data) {
cout << sum(data) << endl;
}
int main() {
vector data = {1, 2, 3};
print_sum(data);
return 0;
}
```
[[1-teaching/ucla-2026-fall-pic-10a/header-implementation-practice-answers|header-implementation-practice-answers]]
.
.
.
.
.
### Additional remark on the "build process".
Roughly speaking, when a C++ project is built (when you press "play" or "run project"), it goes in three stages:
- **Preprocessing**. For each `*.cpp` file, the **preprocessor** looks at all the `#` directives. And the `#include` directive effectively **copy and paste** the content of those files at the line of the `#include`.
- **Compilation**. Then, the **compiler** compiles **each preprocessed** `*.cpp` files separately into machine code, producing "object files". Declarations (often from headers) let the compiler check and compile calls to functions defined in _other_ files.
- **Linking**. Then the **linker** combines the object files (and libraries) into one executable. It connects each use of a function to that function’s actual definition, wherever it lives. If it can’t find a definition, you get a linker error: “undefined reference” in g++, “unresolved external symbol” in Visual Studio, or “Undefined symbol” in Xcode.
That's what's happening when you press that magical "play button" in your IDE. If you want to build C++ project using the terminal, often we have all the files in the same folder, and do `g++ *.cpp -o my_program.exe`.
### Tiny remark on header guards. But you can ignore it for now.
A small but important habit for header files: add a **header guard**, so that the header’s contents are only pasted in once per `.cpp` file, even if it gets `#include`d more than once (which often happens indirectly, when two headers both include a third). Without it, you can get errors from things being defined twice.
The classic way is
```
#ifndef MY_STUFF_HPP
#define MY_STUFF_HPP
// ... header contents go here ...
#endif
```
The name `MY_STUFF_HPP` just has to be unique in your project. The convention is to base it on the file name, in all caps.
Alternatively, you can put this one line at the top of the header:
```
#pragma once
// ... header contents go here ...
```
`#pragma once` isn’t technically part of the C++ standard, but every major compiler supports it. Either approach works. Just pick one and use it in every header.